package top.xcxdl.rural.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.util.concurrent.AtomicDouble;
import top.xcxdl.rural.entity.RuralCourseUser;
import top.xcxdl.rural.entity.RuralQuestion;
import top.xcxdl.rural.mapper.RuralCourseUserMapper;
import top.xcxdl.rural.mapper.RuralQuestionMapper;
import top.xcxdl.rural.service.IRuralQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-05-06
 */
@Service
public class RuralQuestionServiceImpl extends ServiceImpl<RuralQuestionMapper, RuralQuestion> implements IRuralQuestionService {

    @Resource
    private RuralCourseUserMapper courseUserMapper;

    @Override
    public PageInfo<RuralQuestion> getList(Integer pageNo, Integer pageSize, Integer questionType, String key) {
        PageHelper.startPage(pageNo, pageSize);
        QueryWrapper<RuralQuestion> wrapper = new QueryWrapper<>();
        if (questionType != null) {
            wrapper.eq("question_type", questionType);
        }
        if (key != null) {
            wrapper.like("question_title", key)
                    .or()
                    .like("question_options", key);
        }
        //byId倒序
        wrapper.orderByDesc("question_id");
        return new PageInfo<>(solveData(wrapper,false));
    }

    @Override
    public RuralQuestion getDetailById(Integer questionId) {
        RuralQuestion question = baseMapper.selectById(questionId);
        //字符串转json
        question.setQuestionOptionsBody(JSONArray.parseObject(question.getQuestionOptions(), JSONArray.class));
        question.setQuestionCorrectBody(JSONArray.parseObject(question.getQuestionCorrect(), JSONArray.class));
        question.setQuestionOptions(null);
        question.setQuestionCorrect(null);
        return question;
    }

    @Override
    public int doEdit(RuralQuestion question) {
        question.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        if (question.getQuestionId() == null) {
            //新增
            question.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
            return baseMapper.insert(question);
        }else{
            //修改
            return baseMapper.updateById(question) + 1;
        }
    }

    @Override
    public List<RuralQuestion> getListByIds(List<Integer> ids) {
        QueryWrapper<RuralQuestion> wrapper = new QueryWrapper<>();
        wrapper.in("question_id", ids);
        //byId倒序
        return solveData(wrapper,false);
    }

    @Override
    public int doDelete(List<Integer> ids) {
        QueryWrapper<RuralQuestion> wrapper = new QueryWrapper<>();
        wrapper.in("question_id", ids);
        return baseMapper.delete(wrapper);
    }

    @Override
    public List<RuralQuestion> getListByIdsIgnoreCorrect(List<Integer> ids) {
        QueryWrapper<RuralQuestion> wrapper = new QueryWrapper<>();
        wrapper.in("question_id", ids);
        //byId倒序
        return solveData(wrapper, true);
    }

    @Override
    public List<RuralQuestion> getListByUserAndExamIds(List<Integer> ids,RuralCourseUser pojo) {
        QueryWrapper<RuralQuestion> wrapper = new QueryWrapper<>();
        wrapper.in("question_id", ids);
        //byId倒序
        return solveDataByUser(wrapper,pojo);
    }

    private List<RuralQuestion> solveDataByUser(QueryWrapper<RuralQuestion> wrapper,RuralCourseUser pojo) {
        List<RuralQuestion> list = baseMapper.selectList(wrapper);
        JSONObject userAnswer;
        try {
            userAnswer = JSONObject.parseObject(pojo.getAnswer());
        }catch (Exception e){
            userAnswer = new JSONObject();
        }
        //创建并复制userAnswer作为临时变量
        JSONObject finalUserAnswer = userAnswer;
        //初始化得分
        final AtomicDouble score = new AtomicDouble(0.0);
        list.forEach(question -> {
            //字符串转json
            question.setQuestionOptionsBody(JSONArray.parseObject(question.getQuestionOptions(), JSONArray.class));
            question.setQuestionCorrectBody(JSONArray.parseObject(question.getQuestionCorrect(), JSONArray.class));
            if (finalUserAnswer != null && finalUserAnswer.containsKey(String.valueOf(question.getQuestionId()))) {
                //用户作答该题了
                //获取用户的答案
                JSONArray userAnswerBody = finalUserAnswer.getJSONArray(String.valueOf(question.getQuestionId()));
                //获取正确答案
                JSONArray correctAnswerBody = question.getQuestionCorrectBody();
                //获取正确答案数量
                int correctAnswerCount = correctAnswerBody.size();
                final AtomicInteger usercorrectAnswerCount = new AtomicInteger(0);
                correctAnswerBody.forEach(correctAnswer -> {
                    userAnswerBody.forEach(answer -> {
                        if (correctAnswer.equals(answer)) {
                            usercorrectAnswerCount.set(usercorrectAnswerCount.get() + 1);
                        }
                    });
                });
                question.setUserAnswerBody(userAnswerBody);
                //判断用户的答案是否正确
                if (usercorrectAnswerCount.get() == correctAnswerCount && userAnswerBody.size() == correctAnswerCount) {
                    question.setRight(true);
                    score.set(score.get() + Double.parseDouble(question.getQuestionScore()));
                }else{
                    question.setRight(false);
                    question.setQuestionCorrectBody(null);
                }
            }else{
                question.setQuestionCorrectBody(null);
            }
            question.setQuestionOptions(null);
            question.setQuestionCorrect(null);
        });
        pojo.setUserScore(score.get());
        return list;
    }

    private List<RuralQuestion> solveData(QueryWrapper<RuralQuestion> wrapper, boolean ignoreCorrect) {
        List<RuralQuestion> list = baseMapper.selectList(wrapper);
        list.forEach(question -> {
            //字符串转json
            question.setQuestionOptionsBody(JSONArray.parseObject(question.getQuestionOptions(), JSONArray.class));
            if (!ignoreCorrect) {
                question.setQuestionCorrectBody(JSONArray.parseObject(question.getQuestionCorrect(), JSONArray.class));
            }
            question.setQuestionOptions(null);
            question.setQuestionCorrect(null);
        });
        return list;
    }
}
